package cate.game.role.res.guild.po.my.mall;

import cate.common.table.d.GDFunc;
import cate.common.util.GameResult;
import cate.game.role.Role;
import cate.common.table.guild.GuildMallRow;
import cate.game.role.res.guild.msg.mall.MyMallDataResp;
import cate.game.role.res.guild.po.my.MyGuildFuncBase;
import com.fasterxml.jackson.annotation.JsonIgnore;
import easy.java.dev.note.NoteClass;
import easy.java.dev.note.NoteField;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

@NoteClass(value = "我的公会的宝库数据")
public class MyGuildMallPO extends MyGuildFuncBase {
    @NoteField(value = "商店列表")
    public List<GuildMallPO> list;

    @Override
    public void initialize(Role role) {
        super.initialize(role);
        if (list == null) {
            list = new ArrayList<>();
        }
        // 判断商店是否被关闭或者删除
        Iterator<GuildMallPO> it = list.iterator();
        while (it.hasNext()) {
            GuildMallPO mall = it.next();
            GuildMallRow row = role.getGame().table.guild.mall.get(mall.id);
            if (row == null) {
                it.remove();
            }
        }

        for (GuildMallRow row : role.getGame().table.guild.mall.getList()) {
            if (list.stream().noneMatch(mall -> mall.id == row.id)) {
                list.add(new GuildMallPO(role, row.id));
            }
        }
        list.forEach(mall -> mall.initialize(role));
    }

    @JsonIgnore
    public void onDaySpan() {
        for (GuildMallPO mall : list) {
            mall.onDaySpan();
        }
        noticeUpdate();
    }

    /**
     * 获取单个商店信息
     */
    @JsonIgnore
    public GameResult<GuildMallPO> getMall(int mallId) {
        GameResult<GuildMallPO> r = new GameResult<>();

        if (guildFuncOpenCheck()) {
            return r.fail("功能未开启");
        }

        GuildMallRow row = role.getGame().table.guild.mall.get(mallId);
        if (row == null || row.guildLevel > role.getRes().guild.getGuild().basic.level) {
            role.getGame().notice.message(role, "商店不存在或者未开启购买");
            return r.fail("商店不存在或者未开启购买");
        }

        for (GuildMallPO po : list) {
            if (po.id == mallId) {
                r.data = po;
                return r;
            }
        }

        GuildMallPO mall = new GuildMallPO(role, mallId);
        list.add(mall);
        r.data = mall;
        return r;
    }

    public void noticeUpdate() {
        role.sendNow(new MyMallDataResp(this));
    }

    @Override
    public int getFuncId() {
        return GDFunc.GuildFunc.MALL;
    }
}
